package hello;

import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;
import auction.chapter08.ItemTriggerInsert;
import auction.chapter08.ItemTriggerUpdate;

public class HelloWorldTrigger
{
	public static void main(String[] args)throws Exception{
		//triggerInsert();
		triggerUpdate();
	}
	
	public static void triggerInsert()throws Exception{
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();
		
		ItemTriggerInsert i=new ItemTriggerInsert();
		i.setTitle("iii");
		
		s.save(i);
		//s.flush();//force the Insert to occur, but insert will trigger force flush
		s.refresh(i);//Reload the object with a select
		out(i.getCreated());
		
		out("before commit");
		tx.commit();
		out("after commit");
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		//s1.refresh(new ItemTriggerInsert()); refresh a transient object cause error
		s1.refresh(i);
		
		tx1.commit();
		s1.close();
		
		
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
	}
	
	public static void triggerUpdate()throws Exception
	{
		
		Session s=HibernateUtil.getSessionFactory().openSession();
		out(s.getFlushMode());
		Transaction tx=s.beginTransaction();
		
		
		ItemTriggerUpdate i=new ItemTriggerUpdate();
		i.setTitle("trigger update");
		s.save(i);
		//s.flush();
		//s.refresh(i); don't need these lines as <property generated="always"... select will be execute automatically
		out(i.getCreated());//the value will be output.
		
		
		out("before commit");
		tx.commit();
		out("after commit");
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		//update a detached object will cause update sql even this don't change, this will 
		//cause update trigger activated
		/* <class select-before-update="true"... can resolve this */
		//s1.update(i);
		
		
		tx1.commit();
		s1.close();
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
	}
	
	public static void getParent(Class clazz)
	{
		Class parent=clazz.getSuperclass();
	  if(parent !=null)
	  {
			System.out.println("###"+parent.getName());
			getParent(parent);
		}
	}
	
	static void out(Object obj)
	{
		System.out.println("--->"+obj);
	}
}
